from database.database import DBSessionManager
from models import VideoCategory
from typing import List, Dict, Any, Optional


class VideoCategoryDao:
    def __init__(self):
        # 配置会话管理器选项
        self.session_config = {
            "serialize_results": True,  # 启用自动序列化
            "exclude_fields": set()  # 如有需要可排除敏感字段
        }

    def get_list(self) -> List[Dict[str, Any]]:
        """
        获取视频分类列表（自动序列化）

        Returns:
            序列化后的视频分类列表，避免"Instance is not bound to a Session"错误
        """
        with DBSessionManager(**self.session_config) as db:
            return db.all(db.query(VideoCategory))

    def get_by_id(self, category_id: int) -> Optional[Dict[str, Any]]:
        """
        通过ID获取视频分类

        Args:
            category_id: 分类ID

        Returns:
            序列化后的分类对象，如果不存在则返回None
        """
        with DBSessionManager(**self.session_config) as db:
            return db.get_by_id(VideoCategory, category_id)

    def get_by_name(self, name: str) -> Optional[Dict[str, Any]]:
        """
        通过名称获取视频分类

        Args:
            name: 分类名称

        Returns:
            序列化后的分类对象，如果不存在则返回None
        """
        with DBSessionManager(**self.session_config) as db:
            category = db.query(VideoCategory).filter(VideoCategory.name == name).first()
            if category and self.session_config.get("serialize_results", True):
                return db._get_serializer().serialize(category)
            return category

    def create_category(self, category_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        创建视频分类

        Args:
            category_data: 分类数据字典

        Returns:
            创建的序列化分类对象
        """
        # 创建模型实例
        from models import VideoCategory
        category = VideoCategory(**category_data)

        with DBSessionManager(**self.session_config) as db:
            db.add(category)
            db.commit()
            # 返回序列化结果
            return db.get_by_id(VideoCategory, category.id)

    def update_category(self, category_id: int, update_data: Dict[str, Any]) -> int:
        """
        更新视频分类

        Args:
            category_id: 分类ID
            update_data: 更新数据

        Returns:
            更新的记录数
        """
        with DBSessionManager(**self.session_config) as db:
            return db.query(VideoCategory).filter(VideoCategory.id == category_id).update(
                update_data,
                synchronize_session=False
            )

    def delete_category(self, category_id: int) -> bool:
        """
        删除视频分类

        Args:
            category_id: 分类ID

        Returns:
            是否删除成功
        """
        with DBSessionManager(**self.session_config) as db:
            result = db.query(VideoCategory).filter(VideoCategory.id == category_id).delete(
                synchronize_session=False
            )
            db.commit()
            return result > 0